<?php

namespace App\Http\Controllers\Admin;

use App\Models\Project_admin_user;
use Illuminate\Http\Request;
use DB;
use Hash;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class AdminController extends Controller
{
    /**
     *   显示方法管理员
     */
    public function welcomePage()
    {
         $user =  Project_admin_user::all();
         return view('admin.admin.welcome',compact("user"));
    }

    /**
     * 管理员修改或添加页面
     * @param Request $request
     * @param int $id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function adminEditPage(Request $request, $id=0)
    {
         $admin =  Project_admin_user::find($id);
        return view('admin.admin.edit',compact('admin'));
    }


    /**
     * 用户的添加和编辑动作
     * @param Request $request
     * @param int $id
     * @return \Illuminate\Http\RedirectResponse
     */
    public function adminCreateOrSave(Request $request, $id=0)
    {
        $admin = Project_admin_user::find($id);
        if(empty($admin)){      //用户添加
           $admin =  new Project_admin_user();

           if( $admin -> existAdminUsername($request)) {
               return back()->with('error', '用户名已经存在'); //检查用户是否重名

           } elseif ($request->password == $request->repassword && $admin ->createOrSave($request,0)) {
                return redirect(route('admin.welcome'))->with('success','添加成功');

           }
        }

        if( $admin -> existAdminUsername($request)) {
            return back()->with('error', '用户名已经存在'); //检查用户是否重名

        }
        if($admin->createOrSave($request,1)){   //用户编辑

            return redirect(route('admin.welcome'))->with('success','修改成功');
        } else {
            return back()->with('error','修改失败');
        }

        return back()->with('error', '操作失败');
    }

    /**
     * 删除用户的操作
     * @param $id
     * @return \Illuminate\Http\RedirectResponse
     */
    public function adminDel($id)
    {
        $admin = Project_admin_user::find($id);
        if(!empty($admin)){
            $admin ->delete();
            return redirect(route('admin.welcome'))->with('success','删除成功');
        } else {
            return redirect(route('admin.welcome'))->with('error','删除失败');
        }
    }

}
